/**
 * 
 */
package com.lion.jacoco.web.home.module.screen;

import java.io.File;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.dataresolver.Param;
import com.lion.jacoco.biz.JsonUtil;
import com.lion.jacoco.common.GlobalVariable;
import com.lion.jacoco.dao.dataobject.AppConfigDO;
import com.lion.jacoco.manager.AppManager;
import com.lion.jacoco.util.EnvUtil;

/**
 * RefreshExec.java. 2011-12-5下午9:38:31 @author LionBule.
 */
public class Rebuild {
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private AppManager          appManager;
    @Autowired
    private GlobalVariable      globalVariable;

    public void execute(@Param("pid") final int pid, Context context) throws Exception {
        response.setContentType("text/plain; charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if (pid <= 0) {
                out.print(JsonUtil.getFailedResult("parameter value is invalid."));
            } else {
                final AppConfigDO appConfigDO = appManager.queryById(pid);
                String basePath = appConfigDO.getCodePath(globalVariable.getCodePath());
                File buildSh = new File(basePath, EnvUtil.isLinux() ? "build.sh" : "build.bat");
                if (buildSh.exists()) {
                    Thread task = new Thread(new Runnable() {

                        @Override
                        public void run() {
                            appManager.rebulid(appConfigDO);
                        }

                    });
                    task.setName("Rebuild_" + pid);
                    task.start();
                } else {
                    out.print(JsonUtil.getFailedResult("no build.sh/bat script."));
                    return;
                }

            }
            out.print(JsonUtil.getSuccessfulResult("Already in operation, please check the result later."));
        } catch (Exception e) {
            out.print(JsonUtil.getFailedResult("System exception."));
        } finally {
            out.flush();
        }

    }

}
